package com.leetcode.LC_MED;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LC46_2 {
    public List<List<Integer>> permute(int[] nums) {
        ArrayList<List<Integer>> lists = new ArrayList<>();
        if (nums.length==0){
            return lists;
        }
        HashMap<Integer, Boolean> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, true);
        }
        backtrack(lists, nums, 0, map, new ArrayList<>());
        return lists;
    }

    private void backtrack(ArrayList<List<Integer>> lists, int[] nums, int index, HashMap<Integer, Boolean> map, List<Integer> list) {
        if (list.size() == nums.length) {
            lists.add(new ArrayList<>(list));
            return;
        }

        for (int i = index; i < nums.length; i++) {
            if (map.get(nums[i])) {
                list.add(nums[i]);
                map.put(nums[i], false);
                backtrack(lists, nums, index, map, list);
                map.put(list.get(list.size() - 1), true);
                list.remove(list.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        for (List<Integer> list : new LC46_2().permute(new int[]{1, 2, 3})) {
            for (Integer integer : list) {
                System.out.print(integer);
            }
            System.out.println();
        }
    }
}
